package com.masonluo.mlonlinejudge.service.impl;

import com.masonluo.mlonlinejudge.dao.TagRepository;
import com.masonluo.mlonlinejudge.entity.Tag;
import com.masonluo.mlonlinejudge.exceptions.ResourceExistException;
import com.masonluo.mlonlinejudge.mapper.TagMapper;
import com.masonluo.mlonlinejudge.model.bo.TagBo;
import com.masonluo.mlonlinejudge.service.TagService;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @author masonluo
 * @date 2021/1/22 4:15 下午
 */
@Service
public class TagServiceImpl implements TagService {

    private final TagRepository tagRepository;

    private final TagMapper tagMapper;

    public TagServiceImpl(TagRepository tagRepository, TagMapper tagMapper) {
        this.tagRepository = tagRepository;
        this.tagMapper = tagMapper;
    }

    @Override
    public Tag addTag(String tagName) {
        Tag tag = null;
        if ((tag = tagRepository.selectByName(tagName)) == null){
            tag = new Tag(tagName);
            tagRepository.insert(tag);
        }
        return tag;
    }

    @Override
    public boolean deleteTag(String tagName) {
        return tagRepository.deleteByTagName(tagName) > 0;
    }

    @Override
    public List<TagBo> findAll() {
        List<Tag> res = tagRepository.selectAll();
        if (res == null) {
            return Collections.emptyList();
        }
        return tagMapper.to(res);
    }
}
